// request.js
import axios from 'axios';
import {removeNull, tansParams} from './util';
import {ElLoading} from 'element-plus';

// 创建 axios 实例
import {ElNotification} from 'element-plus'
import {ElMessage} from "element-plus";

const service = axios.create({
    baseURL: '/',
    headers: {
        get: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        post: {
            'Content-Type': 'application/json;charset=utf-8'
        }
    },
    // 是否跨站点访问控制请求
    // withCredentials: false,
    timeout: 30000,
    // //请求数据转换
    transformRequest: [(data) => {
        if (Object.prototype.toString.call(data) === '[object FormData]') {
            return data
        } else {
            return JSON.stringify(data)
        }
    }],
    //相应数据转换
    transformResponse: [(data) => {
        if (typeof data === 'string' && data.startsWith('{')) {
            data = JSON.parse(data)
        }
        return data
    }]
})
const ENV = import.meta.env;
let baseUrl = ENV.VITE_NAME_CAR
// 项目相关的请求url数组
let projectUrlArr = ['/web/project/create', '/web/project/update', '/web/project/list']

let loadingInstance;
// 请求拦截器
service.interceptors.request.use((config) => {
    
    // 让每个请求携带自定义 token
    config.headers['Authorization'] = 'token'
    // loadingInstance = ElLoading.service({ fullscreen: true})
    // 项目相关的url 请求头不需要添加x-project字段，反之都需要加该字段
    if(!projectUrlArr.includes(config.url)){
        let projectObj = JSON.parse(sessionStorage.getItem('projectObj') || '{}')
        config.headers['x-project'] = projectObj.projectId || ''
    }
    config.baseURL = baseUrl;
    // if (config.requestBaseUrl == 'outside') {
    //     config.baseURL = ENV.VITE_NAME
    // }else if(config.requestBaseUrl=='carmanage'){
    //     config.baseURL = ENV.VITE_NAME_CAR
    // }else if(config.requestBaseUrl =='uploadFile'){
    //     config.baseURL = ENV.VITE_NAME_IMG_BASEURL
    // }

    if (config.apiType == 'coordinate') {
        config.baseURL = ENV.VITE_NAME_CAR
    }


    if (config.requestBaseUrl == 'outside') {
        config.baseURL = ENV.VITE_NAME
    }
    if (config.apiType == 'CAR') {
        config.baseURL = ENV.VITE_NAME_CAR
    }
    if (config.requestBaseUrl == 'uploadFile') {
        config.baseURL = ENV.VITE_NAME_IMG_BASEURL
    }


    if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    try {
        let userInfo = window.localStorage.getItem('userInfo');

        let user = JSON.parse(userInfo);

        // 判断token存在再做配置
        if (user) {
            config.headers = {
                Accept: 'application/json, text/plain, */*',
                "Token": user.token,
                ...config.headers
            }
        }
    } catch (error) {

    }

    return config

}, (error) => {
    // 错误抛到业务代码
    error.data = {}
    error.data.msg = '服务器异常，请联系管理员！'
    return Promise.resolve(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {

    const status = response.status
    // let msg = '';
    if (status < 200 || status >= 300) {
        // 处理http错误，抛到业务代码
        // msg = showStatus(status)
        // if (typeof response.data === 'string') {
        //     response.data = {msg}
        // } else {
        //     response.data.msg = msg
        // }
        //拦截异常（通知）
        ElNotification({
            title: '提示',
            message: response.data.msg,
            type: 'error'
        })
    }

    if (response.status === 200 && (response.data.code === 200 || response.data.code === 0 || response.data.code === undefined)) {
        return response;
    }else{
        ElMessage.error(response.data.msg);
        Promise.reject();
    }
}, (error) => {
    // 错误抛到业务代码
    // 将400状态码的返回消息传给到前端
    if( error.response &&  error.response.status === 400){
        ElMessage.error(error.response.data.msg);
    }else {
        error.data = {}
        // console.log('error 111',error)
        error.data.msg = '请求超时或服务器异常，请检查网络或联系管理员！'
    }
   

    // ElMessage.error(error.response.data.msg);

    return Promise.resolve(error)


})

const showStatus = (status) => {
    let message = ''
    switch (status) {
        case 400:
            message = '请求错误(400)'
            break
        case 401:
            message = '未授权，请重新登录(401)'
            break
        case 403:
            message = '拒绝访问(403)'
            break
        case 404:
            message = '请求出错(404)'
            break
        case 408:
            message = '请求超时(408)'
            break
        case 500:
            message = '服务器错误(500)'
            break
        case 501:
            message = '服务未实现(501)'
            break
        case 502:
            message = '网络错误(502)'
            break
        case 503:
            message = '服务不可用(503)'
            break
        case 504:
            message = '网络超时(504)'
            break
        case 505:
            message = 'HTTP版本不受支持(505)'
            break
        default:
            message = `连接出错(${status})!`
    }
    return `${message}，请检查网络或联系管理员！`
}


// const post = (url, para, headers) => {

//     return service({
//         url: url,
//         data: para,
//         headers
//     });

// }
// const get = (url, para, headers) => {

//     return service({
//         url: url,
//         data: para,
//         headers
//     });

// }


export default service;
